package top.roadvast.rabbitmq.provider;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.springframework.boot.test.context.SpringBootTest;
import top.roadvast.rabbitmq.utils.RabbitmqUtil;

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 10:38
 * @Version 1.0
 * @Description rabbitmq六种工作模式之一：直连模式
 */
@SpringBootTest
public class DirectProvider {
    public static void main(String[] args) throws IOException {
        final Connection connection = RabbitmqUtil.getConnection();
        final Channel channel = connection.createChannel();
        String[] a = {"info", "warning", "error"};
        //交换机名称：direct_logs；交换机类型：直连
        channel.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        while(true) {
            System.out.println("输入消息：");
            final String message = new Scanner(System.in).nextLine();
            if ("exit".equalsIgnoreCase(message)) {
                break;
            }
            //随机产生日志级别
            String level = a[new Random().nextInt(a.length)];
            System.out.println("当前日志级别：[" + level + "]");
            //参数1: 交换机名
            //参数2: routingKey, 路由键,这里我们用日志级别,如"error","info","warning"
            //参数3: 其他配置属性
            //参数4: 发布的消息数据
            channel.basicPublish("direct_logs", level, null, message.getBytes());
            System.out.println("消息已发出.");
        }
        //关闭连接
        RabbitmqUtil.closeConnection(connection, channel);
    }
}
